<?php

require("./config.php");

if (!isset($_POST['req'])) {
    die("No request provided.");
} else {
    if (filter_input(INPUT_POST, 'req') == "eventos") {

        $json = array("success" => false, "rowCount" => 0, "Elements" => Array(), "CatElements" => Array());

        $categoria = $dbConn->real_escape_string(filter_input(INPUT_POST, 'categoria'));
        $fecha = $dbConn->real_escape_string(filter_input(INPUT_POST, 'fecha'));
        $titulo = $dbConn->real_escape_string(filter_input(INPUT_POST, 'titulo'));

        $query = "SELECT codigo, titulo, descripcion, direccion, DATE_FORMAT(fecha,'%d/%m/%Y %k:%i') AS fecha, categoria "
                . "from evento WHERE codigo is not null";
        if ($categoria != 0) {
            $query = $query . " AND categoria=" . $categoria;
        }
        if ($fecha != '') {
            $query = $query . " AND fecha=STR_TO_DATE('" . $fecha . "', '%d/%m/%Y %k:%i')";
        }
        if ($titulo != '') {
            $query = $query . " AND titulo='" . $titulo . "'";
        }
        $query = $query . ";";

        $result = $dbConn->query($query);
        $i = 0;
        while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
            array_push($json['Elements'], $row);
            $i++;

            $query1 = "select codigo, nombre, descripcion from categoria
                where codigo=" . $row['categoria'] . ";";

            $result1 = $dbConn->query($query1);

            while ($row1 = mysqli_fetch_array($result1, MYSQL_ASSOC)) {
                array_push($json['CatElements'], $row1);
            }
        }

        if ($i > 0) {
            $json['success'] = true;
            $json['rowCount'] = $i;
        }
        print(json_encode($json));
    } else if (filter_input(INPUT_POST, 'req') == "comboCat") {

        $json = array("success" => false, "rowCount" => 0, "Elements" => Array());

        $query = "SELECT codigo, nombre, descripcion from categoria";

        $result = $dbConn->query($query);

        $i = 0;
        while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
            array_push($json['Elements'], $row);
            $i++;
        }

        if ($i > 0) {
            $json['success'] = true;
            $json['rowCount'] = $i;
        }
        print(json_encode($json));
    }
}